package com.efounder.activity;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.drawerlayout.widget.DrawerLayout;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;

import com.efounder.frame.language.MultiLanguageUtil;
import com.efounder.frame.manager.ScreenShotListenManager;
import com.efounder.frame.manager.ScreenShotShareManager;
import com.efounder.frame.utils.DrawerUtils;
import com.efounder.model.BottombarVisibleEvent;
import com.efounder.ospmobilelib.R;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.ScreenShotDialog;
import com.efounder.view.ioc.AbIocEventListener;
import com.efounder.view.ioc.AbIocSelect;
import com.efounder.view.ioc.AbIocView;
import com.efounder.view.titlebar.AbBottomBar;
import com.efounder.view.titlebar.AbTitleBar;
import com.gyf.immersionbar.ImmersionBar;
import com.utilcode.util.AppUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.SizeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.List;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class AbActivity extends SwipeBackActivity implements EasyPermissions.PermissionCallbacks {

    /**
     * 全局的LayoutInflater对象，已经完成初始化.
     */
    public LayoutInflater mInflater;

    /**
     * 全局的Application对象，已经完成初始化.
     */
    public Application abApplication = null;

    /**
     * 总布局.
     */
    public RelativeLayout ab_base = null;

    /**
     * 标题栏布局.
     */
    private AbTitleBar mAbTitleBar = null;

    /**
     * 副标题栏布局.
     */
    private AbBottomBar mAbBottomBar = null;

    /**
     * 主内容布局.
     */
    protected RelativeLayout contentLayout = null;

    /**
     * 1.DrawerLayout
     **/
    private DrawerLayout drawerLayout;
    private RelativeLayout drawerLayout_contentLayout;
    private RelativeLayout drawerLayout_leftLayout;
    private RelativeLayout drawerLayout_rightLayout;

    protected ScreenShotListenManager screenShotListenManager;
    protected ScreenShotShareManager screenShotShareManager;
    //是否监听屏幕截图事件
    private boolean enableScreenShotListen = true;
    //是否支持监听屏幕截图事件
    private boolean isSupportListenScreenShot = false;
    //截屏后弹窗
    private ScreenShotDialog screenShotDialog;


    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(MultiLanguageUtil.setLocal(newBase));
    }

    /**
     * 描述：创建.
     *
     * @param savedInstanceState the saved instance state
     * @see FragmentActivity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        requestWindowFeature(Window.FEATURE_NO_TITLE);

        if (!EasyPermissionUtils.checkWriteAndPhonePermission(this)) {
            //没有存储权限，重启app
            AppUtils.relaunchApp();
            return;
        }
        super.onCreate(savedInstanceState);
        //初始化刷新控件的提示文本
        ResStringUtil.initSmartRefreshLayoutHintText();
        mInflater = LayoutInflater.from(this);

        drawerLayout = initDrawerLayout();
        //最外层布局
        ab_base = new RelativeLayout(this);
        ab_base.setBackgroundColor(getResources().getColor(R.color.transparent));

        //主标题栏
        mAbTitleBar = new AbTitleBar(this);

        //内容布局
        contentLayout = new RelativeLayout(this);
        contentLayout.setPadding(0, 0, 0, 0);

        //副标题栏
        mAbBottomBar = new AbBottomBar(this);

        //填入View
        ab_base.addView(mAbTitleBar, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        mAbTitleBar.setVisibility(View.GONE);


        RelativeLayout.LayoutParams layoutParamsContent = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParamsContent.addRule(RelativeLayout.BELOW, mAbTitleBar.getId());
        layoutParamsContent.addRule(RelativeLayout.ABOVE, mAbBottomBar.getId());
        ab_base.addView(contentLayout, layoutParamsContent);

        RelativeLayout.LayoutParams layoutParamsBottomBar = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mAbBottomBar.setBackground(new ColorDrawable(getResources().getColor(R.color.transparent)));
        layoutParamsBottomBar.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        ab_base.addView(mAbBottomBar, layoutParamsBottomBar);
        //Application初始化
        abApplication = getApplication();

        drawerLayout_contentLayout.addView(ab_base);
        //设置ContentView
        setContentView(drawerLayout, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        // 注册订阅者
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        //初始化截图监听
        initScreenShotListener();

    }

    @Override
    protected void setStatusBarColor() {
        //初始化沉浸式状态栏
        if (immersionBarEnabled()) {
            //https://github.com/gyf-dev/ImmersionBar
            initImmersionBar();
        } else {
            super.setStatusBarColor();
        }
        //fixme  解决输入法遮挡问题
        try {
            //contentLayout.setFitsSystemWindows(true);
            setApplyWindowInsets(contentLayout);
        } catch (Exception e) {
            Log.e("error", "设置setApplyWindowInsets失败" + getClass().getCanonicalName());
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        screenShotShareManager.releaseUshare();
        //关闭activity前关闭弹窗
        if (screenShotDialog != null && screenShotDialog.isShowing()) {
            screenShotDialog.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setBottomBarVisibile(BottombarVisibleEvent event) {
        if (event.isVisible()) {
            getBottomBar().setVisibility(View.VISIBLE);
        } else {
            getBottomBar().setVisibility(View.GONE);
        }
        //设置是否显示bottomBar
    }

    /**
     * 3.初始化 DrawerLayout
     */
    private DrawerLayout initDrawerLayout() {
        final DrawerLayout drawerLayout = (DrawerLayout) mInflater.inflate(R.layout.ab_activity_layout, null);
        drawerLayout_contentLayout = (RelativeLayout) drawerLayout.findViewById(R.id.content_drawer_layout);
        drawerLayout_leftLayout = (RelativeLayout) drawerLayout.findViewById(R.id.left_drawer_layout);
        drawerLayout_rightLayout = (RelativeLayout) drawerLayout.findViewById(R.id.right_drawer_layout);
        //设置默认抽屉是关闭的
        drawerLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            @Override
            public void onGlobalLayout() {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    drawerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    drawerLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                drawerLayout.closeDrawers();
            }
        });
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                DrawerUtils.changeDrawerLayoutContentView(drawerLayout, drawerView, slideOffset);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                Fragment leftFragment = fragmentManager.findFragmentById(R.id.left_drawer_layout);
                Fragment rightFragment = fragmentManager.findFragmentById(R.id.right_drawer_layout);
                if (leftFragment != null) {
                    leftFragment.setUserVisibleHint(true);
                }
                if (rightFragment != null) {
                    rightFragment.setUserVisibleHint(true);
                }

            }

            @Override
            public void onDrawerClosed(View drawerView) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                Fragment leftFragment = fragmentManager.findFragmentById(R.id.left_drawer_layout);
                Fragment rightFragment = fragmentManager.findFragmentById(R.id.right_drawer_layout);
                if (leftFragment != null) {
                    leftFragment.setUserVisibleHint(false);
                }
                if (rightFragment != null) {
                    rightFragment.setUserVisibleHint(false);
                }
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        return drawerLayout;
    }


    /**
     * 描述：用指定的View填充主界面.
     *
     * @param contentView 指定的View
     */
    public void setAbContentView(View contentView) {
        contentLayout.removeAllViews();
        contentLayout.addView(contentView, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        //ioc
        initIocView();
    }

    /**
     * 描述：用指定资源ID表示的View填充主界面.
     *
     * @param resId 指定的View的资源ID
     */
    public void setAbContentView(int resId) {
        setAbContentView(mInflater.inflate(resId, null));
    }

    /**
     * 获取主标题栏布局.
     *
     * @return the title layout
     */
    public AbTitleBar getTitleBar() {
        mAbTitleBar.setVisibility(View.VISIBLE);
        return mAbTitleBar;
    }

    /**
     * 获取副标题栏布局.
     *
     * @return the bottom layout
     */
    public AbBottomBar getBottomBar() {
        return mAbBottomBar;
    }

    /**
     * 底部导航栏，中间有突出大图标时，改变底部高度和内容的margin
     */
    public void changeNavigationHeight() {
        changeContentBottomMargin(11);
        changeBottomBarHeight(60);
    }

    /**
     * 改变中间内容的底部margin
     */
    private void changeContentBottomMargin(int height) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) contentLayout.getLayoutParams();
        params.bottomMargin = -SizeUtils.dp2px(height);
        ab_base.removeView(contentLayout);
        ab_base.addView(contentLayout, params);
    }

    /**
     * 改变bottomBar高度
     */
    private void changeBottomBarHeight(int height) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mAbBottomBar.getLayoutParams();
        params.height = SizeUtils.dp2px(height);
        ab_base.removeView(mAbBottomBar);
        ab_base.addView(mAbBottomBar, params);
    }

    /**
     * 描述：Activity结束.
     *
     * @see android.app.Activity#finish()
     */
    @Override
    public void finish() {
        super.finish();
    }

    /**
     * 描述：设置绝对定位的主标题栏覆盖到内容的上边.
     *
     * @param overlay the new title bar overlay
     */
    public void setTitleBarOverlay(boolean overlay) {
        ab_base.removeAllViews();
        if (overlay) {
            RelativeLayout.LayoutParams layoutParamsFW1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParamsFW1.addRule(RelativeLayout.ABOVE, mAbBottomBar.getId());
            ab_base.addView(contentLayout, layoutParamsFW1);
            RelativeLayout.LayoutParams layoutParamsFW2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParamsFW2.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
            ab_base.addView(mAbTitleBar, layoutParamsFW2);

            RelativeLayout.LayoutParams layoutParamsFW3 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParamsFW3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            ab_base.addView(mAbBottomBar, layoutParamsFW3);

        } else {
            ab_base.addView(mAbTitleBar, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

            RelativeLayout.LayoutParams layoutParamsFW2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParamsFW2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            ab_base.addView(mAbBottomBar, layoutParamsFW2);

            RelativeLayout.LayoutParams layoutParamsFW1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParamsFW1.addRule(RelativeLayout.BELOW, mAbTitleBar.getId());
            layoutParamsFW1.addRule(RelativeLayout.ABOVE, mAbBottomBar.getId());
            ab_base.addView(contentLayout, layoutParamsFW1);
        }
    }

    /**
     * 描述：设置界面显示（忽略标题栏）.
     *
     * @param layoutResID the new content view
     * @see android.app.Activity#setContentView(int)
     */
    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initIocView();
    }

    /**
     * 描述：设置界面显示（忽略标题栏）.
     *
     * @param view   the view
     * @param params the params
     * @see android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
     */
    @Override
    public void setContentView(View view,
                               android.view.ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        initIocView();
    }

    /**
     * 描述：设置界面显示（忽略标题栏）.
     *
     * @param view the new content view
     * @see android.app.Activity#setContentView(android.view.View)
     */
    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        initIocView();
    }

    /**
     * 初始化为IOC控制的View.
     */
    private void initIocView() {
        Field[] fields = getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                try {
                    field.setAccessible(true);

                    if (field.get(this) == null) {
                        AbIocView viewInject = field.getAnnotation(AbIocView.class);
                        if (viewInject != null) {

                            int viewId = viewInject.id();
                            field.set(this, findViewById(viewId));

                            setListener(field, viewInject.click(), AbIocEventListener.CLICK);
                            setListener(field, viewInject.longClick(), AbIocEventListener.LONGCLICK);
                            setListener(field, viewInject.itemClick(), AbIocEventListener.ITEMCLICK);
                            setListener(field, viewInject.itemLongClick(), AbIocEventListener.ITEMLONGCLICK);

                            AbIocSelect select = viewInject.select();
                            if (!TextUtils.isEmpty(select.selected())) {
                                setViewSelectListener(field, select.selected(), select.noSelected());
                            }

                        }
                    } else {
                        continue;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 设置view的监听器.
     *
     * @param field    the field
     * @param select   the select
     * @param noSelect the no select
     * @throws Exception the exception
     */
    private void setViewSelectListener(Field field, String select, String noSelect) throws Exception {
        Object obj = field.get(this);
        if (obj instanceof View) {
            ((AbsListView) obj).setOnItemSelectedListener(new AbIocEventListener(this).select(select).noSelect(noSelect));
        }
    }

    /**
     * 设置view的监听器.
     *
     * @param field      the field
     * @param methodName the method name
     * @param method     the method
     * @throws Exception the exception
     */
    private void setListener(Field field, String methodName, int method) throws Exception {
        if (methodName != null && methodName.trim().length() != 0) {
            Object obj = field.get(this);

            switch (method) {
                case AbIocEventListener.CLICK:
                    if (obj instanceof View) {
                        ((View) obj).setOnClickListener(new AbIocEventListener(this).click(methodName));
                    }
                    break;
                case AbIocEventListener.ITEMCLICK:
                    if (obj instanceof AbsListView) {
                        ((AbsListView) obj).setOnItemClickListener(new AbIocEventListener(this).itemClick(methodName));
                    }
                    break;
                case AbIocEventListener.LONGCLICK:
                    if (obj instanceof View) {
                        ((View) obj).setOnLongClickListener(new AbIocEventListener(this).longClick(methodName));
                    }
                    break;
                case AbIocEventListener.ITEMLONGCLICK:
                    if (obj instanceof AbsListView) {
                        ((AbsListView) obj).setOnItemLongClickListener(new AbIocEventListener(this).itemLongClick(methodName));
                    }
                    break;
                default:
                    break;
            }
        } else {
            return;
        }

    }

    /**
     * 2.获取DrawerLayout
     **/
    public DrawerLayout getDrawerLayout() {
        return drawerLayout;
    }

    public RelativeLayout getDrawerLayoutContentLayout() {
        return drawerLayout_contentLayout;
    }

    public int getDrawerLayoutContentLayoutResId() {
        return R.id.content_drawer_layout;
    }

    public RelativeLayout getDrawerLayoutLeftLayout() {
        return drawerLayout_leftLayout;
    }

    public int getDrawerLayoutLeftLayoutResId() {
        return R.id.left_drawer_layout;
    }

    public RelativeLayout getDrawerLayoutRightLayout() {
        return drawerLayout_rightLayout;
    }

    public int getDrawerLayoutRightLayoutResId() {
        return R.id.right_drawer_layout;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (enableScreenShotListen && isSupportListenScreenShot) {
            screenShotListenManager.startListen();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        screenShotListenManager.stopListen();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("提示").setRationale(R.string.permission_remind_again).build().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        screenShotShareManager.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 初始化截图监听
     */
    private void initScreenShotListener() {

        isSupportListenScreenShot = EnvSupportManager.isSupportListenScreenShot();
        screenShotListenManager = ScreenShotListenManager.newInstance(this);
        screenShotShareManager = new ScreenShotShareManager(this);
        screenShotListenManager.setListener(
                new ScreenShotListenManager.OnScreenShotListener() {
                    @Override
                    public void onShot(String imagePath) {
                        //这里我们拿到了截屏的图片
                        LogUtils.i(imagePath);
                        if (AbActivity.this != null && !AbActivity.this.isFinishing()) {
                            screenShotDialog = new ScreenShotDialog(AbActivity.this, imagePath);
                            screenShotDialog.setOnShareClickListener(new ScreenShotDialog.ShareClickListener() {
                                @Override
                                public void onShareClick(String imagePath) {
                                    gotoShare(imagePath);
                                }
                            });
                            screenShotDialog.show();
                        }

                    }
                }
        );

    }


    /**
     * 去分享
     *
     * @param imagePath
     */
    private void gotoShare(final String imagePath) {
        screenShotShareManager.shareSceenShotPic(imagePath);
    }

    /**
     * 是否允许监听屏幕截图
     *
     * @param enable
     */
    public void setEnableScreenShotListen(boolean enable) {
        enableScreenShotListen = enable;
    }

    public void initImmersionBar() {
        ImmersionBar.with(this).init();
    }

    /**
     * 是否可以实现沉浸式，当为true的时候才可以执行initImmersionBar方法
     * Immersion bar enabled boolean.
     *
     * @return the boolean
     */
    public boolean immersionBarEnabled() {
        return EnvSupportManager.isUseTransparentStatus();
    }
}
